# !/usr/bin/env python
# coding=utf-8
# @Time    : 2017/11/1 14:51
# @Author  : 6imensiva
# @Site    : https://gitee.com/dimensiva/app_server.git
# @File    : my_request.py
# @Software: PyCharm
# @Version: 3.5.4
"""
my_request,my_request2是python2
my_request3，my_request4是python3
my_request4处理了资源释放的问题,代码更优雅
my_request5用第三方库requests，更简单
"""
import urllib.request
import urllib.parse
import json
from utils import my_exception, XML2Dict, my_dict
import requests
# from log import mylog


# def my_request(method, url, param_dict=None, timeout=None, header=None, parse_format=None):
# 	"""
# 	封装urllib2的http请求函数
#
# 	:param method: 支持GET和POST
# 	:param url: 请求地址
# 	:param param_dict: POST用的参数字典，转成json
# 	:param timeout: 请求超时时间，秒为单位
# 	:param header: 请求头
# 	:param parse_format: None-返回的原始內容 'json'-返回json字典 'xml'-返回xml字典
# 	:return: http状态码,返回指定內容
# 	"""
# 	if header:
# 		req = urllib2.Request(url, headers=header)
# 	else:
# 		req = urllib2.Request(url)
#
# 	try:
# 		if method == 'GET':
# 			resp = urllib2.urlopen(req, timeout=timeout)
# 		elif method == 'POST':
# 			#decode('unicode-escape'): 把字符串中'/u'部分去掉
# 			resp = urllib2.urlopen(req, data=json.dumps(param_dict).decode('unicode-escape').encode('utf-8'), timeout=timeout)
# 		else:
# 			pass
# 	except Exception as e:
# 		if resp is not None:
# 			resp.close()
# 		raise e
#
# 	code = resp.getcode()
# 	text = resp.read()
# 	resp.close()
#
# 	if not parse_format:
# 		return code, text
# 	elif parse_format == 'json':
# 		return code, my_json.loads(text) # 原生的loads之后就由str变成unicode了
# 	elif parse_format == 'xml':
# 		return code, XML2Dict.parsexml(text)
# 	else:
# 		return code, text
#
#
# def my_request2(method, url, param_dict=None, timeout=None, header=None, parse_format=None):
# 	"""
# 	封装urllib2的http请求函数
#
# 	:param method: 支持GET和POST
# 	:param url: 请求地址
# 	:param param_dict: POST用的参数字典，转成json
# 	:param timeout: 请求超时时间，秒为单位
# 	:param header: 请求头
# 	:param parse_format: None-返回的原始內容 'json'-返回json字典 'xml'-返回xml字典
# 	:return: 返回指定內容
# 	"""
# 	if header:
# 		req = urllib2.Request(url, headers=header)
# 	else:
# 		req = urllib2.Request(url)
#
# 	resp = None
# 	if method == 'GET':
# 		resp = urllib2.urlopen(req, timeout=timeout)
# 	elif method == 'POST':
# 		# decode('unicode-escape'): 把字符串中'/u'部分去掉
# 		resp = urllib2.urlopen(req, data=json.dumps(param_dict).decode('unicode-escape').encode('utf-8'),
# 		                       timeout=timeout)
# 	else:
# 		pass
# 	text = resp.read()
# 	resp.close()
#
# 	if not parse_format:
# 		return text
# 	elif parse_format == 'json':
# 		return my_json.loads(text) # 原生的loads之后就由str变成unicode了
# 	elif parse_format == 'xml':
# 		return XML2Dict.parsexml(text)
# 	else:
# 		return text


def my_request3(url, param_dict=None, timeout=None, header=None, parse_format=None):
	request_msg = 'request err:' + ' url=' + url + \
	          ' param_dict=' + param_dict + ' timeout=' + timeout + ' header=' + header
	print(request_msg)

	if param_dict:
		data = urllib.parse.urlencode(param_dict)
		if header:
			req = urllib.request.Request(url, data.encode(encoding='utf-8'), header)
		else:
			req = urllib.request.Request(url, data.encode(encoding='utf-8'))
	else:
		if header:
			req = urllib.request.Request(url, headers=header)
		else:
			req = urllib.request.Request(url)

	response = urllib.request.urlopen(req, timeout=timeout)
	text = bytes.decode(response.read())
	if not parse_format:
		return text
	elif parse_format == 'json':
		return json.loads(text)
	elif parse_format == 'xml':
		return XML2Dict.parsexml(text)
	else:
		return text


def my_request4(method, url, param_dict=None, timeout=None, parse_format=None):
	request_msg = 'request err:method=' + method + ' url=' + url + \
	          ' param_dict=' + param_dict + ' timeout=' + timeout
	print(request_msg)

	req = urllib.request.Request(url)
	req.method = method
	if method == 'GET':
		with urllib.request.urlopen(req, timeout=timeout) as f:
			text = f.read().decode('utf-8')
	elif method == 'POST' or method == 'PUT':
		req.add_header('Content-Type', 'application/json')
		with urllib.request.urlopen(req, data=my_dict.dict2byte(param_dict), timeout=timeout) as f:
			text = f.read().decode('utf-8')
	else:
		raise my_exception.MyException('unknown method='+method)
	if not parse_format:
		return text
	elif parse_format == 'json':
		return json.loads(text)
	elif parse_format == 'xml':
		return XML2Dict.parsexml(text)
	else:
		return text


def my_request5(method, url, param_dict=None, timeout=None, parse_format=None):
	request_msg = 'request err:method=' + method + ' url=' + url + \
	          ' param_dict=' + param_dict + ' timeout=' + timeout
	print(request_msg)

	if method == 'GET':
		r = requests.get(url, timeout=timeout)
	elif method == 'POST':
		header = {'Content-Type': 'application/json'}
		r = requests.post(url, data=my_dict.dict2byte(param_dict), timeout=timeout, headers=header)
	elif method == 'PUT':
		header = {'Content-Type', 'application/json'}
		r = requests.put(url, data=my_dict.dict2byte(param_dict), timeout=timeout, headers=header)
	else:
		raise my_exception.MyException('unknown method=' + method)
	if not parse_format:
		return r.text
	elif parse_format == 'json':
		print(r.text)
		return r.json()
	elif parse_format == 'xml':
		return XML2Dict.parsexml(r.text)
	else:
		return r.text



if __name__ == '__main__':
	# print(my_request3('http://127.0.0.1:9020/api/order/list', timeout=5))
	# print(my_request4('PUT', 'http://127.0.0.1:9020/api/order/add', timeout=5, param_dict={'123':'aaa'}))
	print(my_request5('GET', 'http://127.0.0.1:9020/api/order/add', timeout=5, param_dict={'123': 'aaa'}))